<script setup lang="ts">
import { ref } from 'vue'
import { useRoute,useRouter,RouterLink, RouterView } from 'vue-router'
import axios from 'axios'
import {ElMessage, type FormInstance, type FormRules} from 'element-plus'

let booksData=ref()
let router=useRouter();
let formData=ref({
  name:"",
  type:"",
  information:""
})
const handleClick = async (scope:any) => {
  console.log(scope)
  router.push({ name: 'detail', query: { id: scope.row.id } })
}

const handleClick2 = async (scope:any) => {
  console.log(scope)
  router.push({ name: 'edit', query: { id: scope.row.id } })
}

axios.get("http://localhost:8080/book").then((res)=>{
    console.log(res)
    booksData.value=res.data
})

const submit=()=>{
  console.log(formData);
  axios.get('http://localhost:8080/search',{params:formData.value}).then((res)=>{
    booksData.value=res.data;
  })
}


// 删除处理函数
const handleDelete = async (scope: any) => {
  try {
    const id = scope.row.id;
    console.log('要删除的书籍ID:', id); // 打印要删除的书籍ID，确认是否正确
    await axios.delete(`http://localhost:8080/book/${id}`);
    ElMessage.success('删除成功');
    // 重新获取数据更新表格
    axios.get("http://localhost:8080/book").then((res) => {
      booksData.value = res.data
    })
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

//  新增
const goToNewPage = () => {
  router.push({ name: 'new' })
}

</script>

<template>

    <form>
      书名:<input type="text" v-model="formData.name">
      类型:<input type="text" v-model="formData.type">
      描述:<input type="text" v-model="formData.information">
<!--      前端常见的表单提交导致页面刷新问题。在 Vue 应用中，点击 button 按钮如果不指定 type 类型，默认会触发表单提交行为，导致页面刷新-->
<!--      <button  >搜索</button>-->
      <el-button type="primary" @click="submit">搜索</el-button>
      <el-button type="primary" @click="goToNewPage">新建</el-button>
    </form>
    <!-- <div v-if="booksData"> -->
      <el-table :data="booksData">
        <el-table-column prop="id" label="书本编号"></el-table-column>
        <el-table-column prop="name" label="书本名称"></el-table-column>
        <el-table-column prop="type" label="书本类型"></el-table-column>
        <el-table-column prop="information" label="书本描述"></el-table-column>
        <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">

        <!-- handleClick 函数期望接收整个 scope 对象 -->
        <!-- 这会导致 scope.row.id 在函数内部无法正常工作，因为 scope 实际接收到的是行索引而非完整的作用域对象 -->
        <!-- <el-button type="primary" @click="handleClick(scope.$index)">查看</el-button> -->
        <el-button type="primary" @click="handleClick(scope)">查看</el-button>
        <el-button type="warning" @click="handleClick2(scope)">编辑</el-button>
        <el-button type="danger" @click="handleDelete(scope)">删除</el-button>
      </template>
      </el-table-column>
    </el-table>
    <!-- </div> -->

  <!-- <RouterView /> -->
</template>

<style scoped>

</style>
